package services;

import dao.ChapterDAO;
import dao.ComicDAO;
import dao.HistoryDAO;
import model.Chapter;
import model.Comic_s;
import model.History;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import utils.C3P0Util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 提供历史记录操作的业务
 */
public class HistoryServices {
    private HistoryDAO historyDAO;

    public HistoryServices() {
        historyDAO = new HistoryDAO();
    }

    /**
     * 增加历史的操作，有则更新，无则插入，然后限制在一定数量
     *
     * @param userName  用户名
     * @param comicId   漫画id
     * @param chapterId 章节id
     */
    public void addHistory(String userName, int comicId, int chapterId) {
        historyDAO.addHistory(userName, comicId, (chapterId));
    }

    /**
     * 查询有无这个历史记录
     *
     * @param userName 用户名
     * @param comicId  漫画id
     * @return History
     */
    public History checkHistory(String userName, String comicId) {
        return historyDAO.checkHistory(userName, Integer.parseInt(comicId));
    }

    /**
     * 为list<History>中的每一个history绑定漫画和章节的详细信息
     *
     * @param list list
     */
    private void bindComicAndChapter(List<History> list) {

        ComicDAO comicDAO = new ComicDAO();
        ChapterDAO chapterDAO = new ChapterDAO();
        //公用的coon
        Connection coon = C3P0Util.getConnection();
        //遍历history
        for (History history : list) {
            //绑定漫画
            Comic_s comic = comicDAO.getComic_sDetail(history.getComic_id(), coon);
            history.setComic(comic);//为每一个history绑定一个comic，以获取该comic的详细信息
            //绑定章节
            int chapterId = history.getChapter_id();
            if (chapterId != 0) {
                Chapter chapter = chapterDAO.getChapterDetail(history.getChapter_id());
                history.setChapter(chapter);
            }
        }
    }

    /**
     * 获得list<History>,通过服务器的数据库
     *
     * @param userName 用户名
     * @return List
     */
    public List<History> getHistoryByServer(String userName) {
        List<History> list = historyDAO.getUserHistory(userName);
        bindComicAndChapter(list);
        return list;
    }

    /**
     * json字符串转化为list<History>
     *
     * @param json     字符串
     * @param userName 用户名
     * @return
     */
    private List<History> jsonToListBean(String userName, String json) {
        List<History> list = new ArrayList<History>();

        JSONArray jsonArray = JSONArray.fromObject(json);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            History history = new History();
            history.setUser_name(userName);
            history.setChapter_id(jsonObject.getInt("chapter_id"));
            history.setComic_id(jsonObject.getInt("comic_id"));
            history.setTime(new Date(jsonObject.getLong("time")));

            list.add(history);
        }

        return list;
    }

    /**
     * 获得list<History>,通过客户端的json字符串
     *
     * @param json
     * @return
     */
    public List<History> getHistoryByHost(String json) {
        List<History> list = null;

        try {
            list = jsonToListBean("", URLDecoder.decode(json, "UTF-8"));
            //根据时间逆向数组排序
            Collections.sort(list, new Comparator<History>() {
                @Override
                public int compare(History o1, History o2) {
                    if (o1.getTime().after(o2.getTime())) {//o1的时间比o2晚
                        return -1;//返回负数将排在前面
                    }
                    return 1;
                }
            });

            //绑定动画和漫画
            bindComicAndChapter(list);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 删除某个history
     *
     * @param userName 用户名
     * @param comicId  漫画id
     */
    public boolean deleteHistory(String userName, String comicId) {
        return historyDAO.deleteHistory(userName, Integer.parseInt(comicId));
    }

    /**
     * 将客户端的历史记录插入数据库
     *
     * @param json     json
     * @param userName 用户名
     * @throws UnsupportedEncodingException
     */
    public void addHostHistories(String json, String userName) {
        List<History> list = null;
        try {

            list = jsonToListBean(userName, URLDecoder.decode(json, "UTF-8"));
            for (History history : list) {
                Timestamp timestamp = new Timestamp(history.getTime().getTime());//date转timestamp
                historyDAO.addHistory(userName, history.getComic_id(), history.getChapter_id(), timestamp);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
